package org.mobile.api.web;

import java.util.concurrent.TimeoutException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.sf.json.JSONObject;

import org.mobile.model.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


/**
 * @author sbwkl
 */
@Controller
@RequestMapping("/api/gateway.htm")
public class GatewayController {

    @Autowired
    private MemcachedClient memcachedClient;

    /**
     * @param request
     *            HttpServletRequest
     * @param response
     *            HttpServletResponse
     * @param map
     *            参数集合
     */
    @RequestMapping(method = RequestMethod.POST)
    public void gatewayPost(HttpServletRequest request,
            HttpServletResponse response, ModelMap map) {
        // TODO 接口验签操作

        String method = request.getParameter("method");
        /**
         * 换取access token
         */
        if("api.system.oauth.token".equals(method)) {
            String code = request.getParameter("code");
            try {
                String accessToken = memcachedClient.get(code);
                map.put("access_token", accessToken);
            } catch(TimeoutException e) {
                e.printStackTrace();
            } catch(InterruptedException e) {
                e.printStackTrace();
            } catch(MemcachedException e) {
                e.printStackTrace();
            }
        /**
         * 获取用户信息
         */
        } else if("api.user.info.share".equals(method)) {
            String accessToken = request.getParameter("access_token");
            try {
                JSONObject user = memcachedClient
                        .get(Constants.ZSHT_DOCTOR + accessToken);
                map.put("login_name", user.optString("login_name"));
            } catch(TimeoutException e) {
                e.printStackTrace();
            } catch(InterruptedException e) {
                e.printStackTrace();
            } catch(MemcachedException e) {
                e.printStackTrace();
            }
        }
    }
}
